
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="第十六章 Javascript基础">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>第十六章 Javascript基础 [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        第十六章 Javascript基础
      </h1>
      <span>
        
        <time class="time" datetime="2017-05-07T11:55:09.000Z">
        2017-05-07
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <h2 id="一、JS如何引入及基本语法规范"><a href="#一、JS如何引入及基本语法规范" class="headerlink" title="一、JS如何引入及基本语法规范"></a><div id="title">一、JS如何引入及基本语法规范</div></h2><p><strong>1.页面内的script代码书写格式</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">	code.....</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>2.script标签写在页面的哪个位置？</strong></p>
<blockquote>
<p>2.1.<strong>页面head里和body后都可以写</strong></p>
<p>2.2.<strong>一般我们建议写在body之后</strong></p>
</blockquote>
<p><strong>3.是否可以引入第三方js文件？</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;script type=<span class="string">'text/javascript'</span> src=<span class="string">'/path/to/js文件'</span>&gt;<span class="xml"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br></pre></td></tr></table></figure>

<p><strong>4.JS的注释方式</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 这个是单行注释</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">这个是多行注释</span></span><br><span class="line"><span class="comment">**/</span></span><br></pre></td></tr></table></figure>

<p><strong>5.JS的结束符号,以分号为结束符号，如果没有的话，js引擎会自动加上</strong></p>
<hr>
<h2 id="二、变量声明"><a href="#二、变量声明" class="headerlink" title="二、变量声明"></a><div id="title">二、变量声明</div></h2><p><strong>命名规范</strong> </p>
<blockquote>
<p>1.JS的变量名 可以使用 _，数字，字母，$ 组成，且不能以数字开头</p>
</blockquote>
<blockquote>
<p>2.声明变量使用 <font>var 变量名</font> 来进行声明</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">34</span>;</span><br><span class="line"><span class="keyword">var</span> b = <span class="number">45</span>;</span><br><span class="line"><span class="built_in">console</span>.log(a+b);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> $ = <span class="string">'jquery'</span></span><br><span class="line">alert($);</span><br><span class="line"></span><br><span class="line">c = <span class="number">56</span>;</span><br><span class="line">alert(c);</span><br></pre></td></tr></table></figure>

<p><strong><font color="red">注意：变量名区分大小写str和Str不是一个变量，也就是js对变量名的大小写是敏感的</font></strong> </p>
<hr>
<h2 id="三、JS变量类型"><a href="#三、JS变量类型" class="headerlink" title="三、JS变量类型"></a><div id="title">三、JS变量类型</div></h2><p><strong>js的变量类型主要包括：</strong></p>
<ul>
<li>数值</li>
<li>字符串</li>
<li>布尔</li>
<li>undefined</li>
<li>数组</li>
<li>对象</li>
</ul>
<p><strong>1) 数值类型</strong><br>js不区分 整型和浮点型</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">23</span>;</span><br><span class="line"><span class="keyword">var</span> b = <span class="number">34</span>;</span><br><span class="line"><span class="built_in">console</span>.log(a);</span><br></pre></td></tr></table></figure>

<p><strong>常用的方法</strong></p>
<ul>
<li>parseInt(..)    将某值转换成数字， 不成功则NAN</li>
<li>parseFloat(..) 将某值转换成浮点数，不成功则NAN<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">parseInt</span>(<span class="string">'3.5'</span>)</span><br><span class="line"><span class="built_in">parseFloat</span>(<span class="string">'2.3dd'</span>)</span><br></pre></td></tr></table></figure>

</li>
</ul>
<p><strong>2) 字符串类型</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">'hello'</span></span><br><span class="line"><span class="keyword">var</span> b = <span class="string">'world'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> str = a + b;</span><br><span class="line"><span class="built_in">console</span>.log(str);</span><br></pre></td></tr></table></figure>

<p><strong>常用的方法:</strong></p>
<ul>
<li><p>obj.length　　　　　　　　　　　　　　　长度</p>
</li>
<li><p>obj.trim()　　　　　　　　　　　　　　　移除空白</p>
</li>
<li><p>obj.trimLeft()</p>
</li>
<li><p>obj.trimRight()</p>
</li>
<li><p>obj.charAt(n)　　　　　　　　　　　　　返回字符串中的第n个字符</p>
</li>
<li><p>obj.concat(value, …)　　　　　　　　 拼接</p>
</li>
<li><p>obj.indexOf(substring,start)　　　　子序列位置</p>
</li>
<li><p>obj.substring(from, to)　　　　　　　根据索引获取子序列</p>
</li>
<li><p>obj.slice(start, end)　　　　　　　　切片</p>
</li>
<li><p>obj.toLowerCase()　　　　　　　　　　大写</p>
</li>
<li><p>obj.toUpperCase()　　　　　　　　　　小写</p>
</li>
<li><p>obj.split(delimiter, limit)　　　　　分割</p>
</li>
</ul>
<p><strong><font color="red">注意：拼接字符串的操作符：”+”</font></strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="number">3</span> + <span class="number">2</span> + <span class="string">"hello"</span> + <span class="number">5</span> + <span class="string">"world"</span>);</span><br><span class="line"><span class="string">``</span><span class="string">` </span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">**3) 布尔类型**</span></span><br><span class="line"><span class="string">**true和false要求是要小写的**</span></span><br><span class="line"><span class="string">`</span><span class="string">``</span>javascript</span><br><span class="line"><span class="keyword">var</span> a = <span class="literal">true</span>;</span><br><span class="line"><span class="keyword">var</span> b = <span class="literal">false</span>;</span><br></pre></td></tr></table></figure>

<p><strong>4) 数组型</strong><br><strong>javascript中的数组类似于我们Python中的列表</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="string">'alex'</span>,<span class="string">'凤姐'</span>,<span class="string">'苍老师'</span>];</span><br><span class="line"><span class="built_in">console</span>.log(arr[<span class="number">2</span>]);</span><br></pre></td></tr></table></figure>

<p><strong>常用的方法:</strong></p>
<ul>
<li><p>obj.length          数组的大小</p>
</li>
<li><p>obj.push(ele)       尾部追加元素</p>
</li>
<li><p>obj.pop()           尾部获取一个元素</p>
</li>
<li><p>obj.unshift(ele)    头部插入元素</p>
</li>
<li><p>obj.shift()         头部移除元素</p>
</li>
<li><p>obj.slice( )        切片</p>
</li>
<li><p>obj.reverse( )      反转</p>
</li>
<li><p>obj.join(sep)       将数组元素连接起来以构建一个字符串</p>
</li>
<li><p>obj.concat(val,..)  连接数组</p>
</li>
<li><p>obj.sort( )         对数组元素进行排序</p>
</li>
</ul>
<p><strong>此时如果我们想要循环数组中的内容，我们可以这样:</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="string">'alex'</span>,<span class="string">'凤姐'</span>,<span class="string">'苍老师'</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; arr.length; i++)&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(arr[i]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>5) 对象型</strong><br><strong>javascript中的对象类似于我们Python中的字典,json数据格式</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> info = &#123;<span class="string">"name"</span>:<span class="string">'alex'</span>,<span class="string">"age"</span>:<span class="number">73</span>&#125;</span><br><span class="line"><span class="built_in">console</span>.log(info.name);</span><br><span class="line"><span class="built_in">console</span>.log(info[<span class="string">'name'</span>]);</span><br></pre></td></tr></table></figure>

<p><strong>此时如果我们想要循环对象中的内容，我们可以这样:</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> info = &#123;<span class="string">"name"</span>:<span class="string">'alex'</span>,<span class="string">"age"</span>:<span class="number">73</span>&#125;</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i <span class="keyword">in</span> info)&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(info[i]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="四、运算符介绍"><a href="#四、运算符介绍" class="headerlink" title="四、运算符介绍"></a><div id="title">四、运算符介绍</div></h2><p><strong>1) 算数运算符</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">+   -    *    <span class="regexp">/     %       ++        --</span></span><br></pre></td></tr></table></figure>

<p><strong>2) 比较运算符</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;   &gt;=   <span class="xml"><span class="tag">&lt;    &lt;=    <span class="string">!</span>=    ==    ===   <span class="string">!</span>==</span></span></span><br></pre></td></tr></table></figure>

<p><strong>3) 逻辑运算符</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&amp;&amp;   ||   ！</span><br></pre></td></tr></table></figure>

<p><strong>4) 赋值运算符</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">=  +=   -=  *=   <span class="regexp">/=</span></span><br></pre></td></tr></table></figure>

<hr>
<h2 id="五、流程控制"><a href="#五、流程控制" class="headerlink" title="五、流程控制"></a><div id="title">五、流程控制</div></h2><p><strong>1）if–else语句</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (条件)&#123;</span><br><span class="line">  当条件为 <span class="literal">true</span> 时执行的代码</span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">  当条件不为 <span class="literal">true</span> 时执行的代码</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>2）if–else if–else语句</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (条件 <span class="number">1</span>)&#123;</span><br><span class="line">  当条件 <span class="number">1</span> 为 <span class="literal">true</span> 时执行的代码</span><br><span class="line">&#125;<span class="keyword">else</span> <span class="keyword">if</span> (条件 <span class="number">2</span>)&#123;</span><br><span class="line">  当条件 <span class="number">2</span> 为 <span class="literal">true</span> 时执行的代码</span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">  当条件 <span class="number">1</span> 和 条件 <span class="number">2</span> 都不为 <span class="literal">true</span> 时执行的代码</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>3)switch语句</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> day=<span class="keyword">new</span> <span class="built_in">Date</span>().getDay();</span><br><span class="line"><span class="keyword">switch</span> (day)&#123;</span><br><span class="line"><span class="keyword">case</span> <span class="number">0</span>:</span><br><span class="line">  x=<span class="string">"Today it's Sunday"</span>;</span><br><span class="line">  <span class="keyword">break</span>;</span><br><span class="line"><span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">  x=<span class="string">"Today it's Monday"</span>;</span><br><span class="line">  <span class="keyword">break</span>;</span><br><span class="line"><span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">  x=<span class="string">"Today it's Tuesday"</span>;</span><br><span class="line">  <span class="keyword">break</span>;</span><br><span class="line"><span class="keyword">case</span> <span class="number">3</span>:</span><br><span class="line">  x=<span class="string">"Today it's Wednesday"</span>;</span><br><span class="line">  <span class="keyword">break</span>;</span><br><span class="line"><span class="keyword">default</span>:</span><br><span class="line">  x=<span class="string">"Looking forward to the Weekend"</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>4）while循环语句</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> (i&lt;<span class="number">5</span>)&#123;</span><br><span class="line">  x=x + <span class="string">"The number is "</span> + i + <span class="string">"&lt;br&gt;"</span>;</span><br><span class="line">  i++;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>5) 三元运算符</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">3</span>;</span><br><span class="line"><span class="keyword">var</span> b = <span class="number">5</span>;</span><br><span class="line"></span><br><span class="line">c = a &gt; b ? a : b</span><br><span class="line"><span class="built_in">console</span>.log(c);</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="六、函数"><a href="#六、函数" class="headerlink" title="六、函数"></a><div id="title">六、函数</div></h2><p><strong>1.函数的定义</strong><br><strong><font color="red"> 注意：javascript中的函数和python的中函数大同小异，唯一不同的是函数的定义方式</font></strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>正常的定义方式  ----  普通青年</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">a,b</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="number">2.</span>匿名函数的定义方式 ---- <span class="number">2</span>B青年</span><br><span class="line"><span class="keyword">var</span> sum = <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="number">3.</span>立即调用函数方式 ----- 文艺青年</span><br><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> a + b;</span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>

<p><strong>2.函数的全局变量和局部变量</strong></p>
<blockquote>
<p>全局变量：定义在函数外部，<font color="red">推荐使用var进行显式声明</font><br>局部变量：定义在函数内部，<font color="red">必须使用var进行显式声明</font></p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 全局变量（不推荐第二种方式）</span></span><br><span class="line"><span class="keyword">var</span> name = <span class="string">"zekai"</span>;</span><br><span class="line">age = <span class="number">73</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="comment">// 局部变量</span></span><br><span class="line">	<span class="keyword">var</span> height = <span class="number">178</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 默认全局变量</span></span><br><span class="line">	leg = <span class="number">4</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>3.函数作用域</strong><br>首先在函数内部查找变量，找不到则到外层函数查找，逐步找到最外层<br>即window对象，并操作window对象上的属性</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="built_in">window</span>.a, <span class="built_in">window</span>.b);</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="keyword">var</span> a = <span class="string">"local"</span>;</span><br><span class="line">    b = <span class="string">"global"</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="built_in">window</span>.a, <span class="built_in">window</span>.b);</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="七、常见的模块和常用方法"><a href="#七、常见的模块和常用方法" class="headerlink" title="七、常见的模块和常用方法"></a><div id="title">七、常见的模块和常用方法</div></h2><h3 id="1-日期类Date"><a href="#1-日期类Date" class="headerlink" title="1.日期类Date"></a>1.日期类Date</h3><p>var d = new Date();　　　返回当日的日期和时间</p>
<ul>
<li>getYear()        　　　　　　　从 Date 对象返回一个月中的某一天 (1 ~ 31)</li>
<li>getFullYear()　　　　　从 Date 对象以四位数字返回年份</li>
<li>getMonth()    　　　　　　从 Date 对象返回月份 (0 ~ 11)    </li>
<li>getDate() 　　　　　　　从 Date 对象返回一个月中的某一天 (1 ~ 31)</li>
<li>getDay()        　　　　　　　从 Date 对象返回一周中的某一天 (0 ~ 6)</li>
<li>getHours()    　　　　　    返回 Date 对象的小时 (0 ~ 23)</li>
<li>getMinutes()　　　　　返回 Date 对象的分钟 (0 ~ 59)</li>
<li>getSeconds()     　　　　返回 Date 对象的秒数 (0 ~ 59)</li>
</ul>
<p><strong>案例 — 时钟显示：</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">当前时间：&lt;input type=<span class="string">'text'</span> value=<span class="string">''</span> id=<span class="string">'time'</span>/&gt;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">change</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="keyword">var</span> time = <span class="built_in">document</span>.getElementById(<span class="string">"time"</span>);</span><br><span class="line">	<span class="keyword">var</span> d = <span class="keyword">new</span> <span class="built_in">Date</span>();</span><br><span class="line">	time.value = d;</span><br><span class="line">&#125;</span><br><span class="line">setInterval(change, <span class="number">1000</span>);</span><br></pre></td></tr></table></figure>

<h3 id="2-Math数学对象"><a href="#2-Math数学对象" class="headerlink" title="2.Math数学对象"></a>2.Math数学对象</h3><ul>
<li>Math.ceil(数值)    　　　　向上取整</li>
<li>Math.floor(数值)        　　　向下取整</li>
<li>Math.round(数值)    　　　把数四舍五入为最接近的整数</li>
<li>Math.min(数值1,数值2)　　　返回最小值</li>
<li>Math.max(数值1,数值2) 　　返回最大值</li>
<li>Math.random()   　　　　　获得0-1之间的随机数</li>
</ul>
<h3 id="3-常见的其他函数"><a href="#3-常见的其他函数" class="headerlink" title="3.常见的其他函数"></a>3.常见的其他函数</h3><p><strong>在数据传输流程中，json是以文本，即字符串的形式传递的，而JS操作的是JSON对象，所以，<font color="red">JSON对象和JSON字符串之间的相互转换是关键</font>，例如：</strong></p>
<p><strong>JSON字符串：</strong></p>
<blockquote>
<p>var str1 = ‘{ “name”: “alex”, “sex”: “feng” }’;</p>
</blockquote>
<p><strong>JSON对象：</strong></p>
<blockquote>
<p>var str2 = { “name”: “alex”, “sex”: “feng” };</p>
</blockquote>
<p><strong>JSON字符串转换成JSON对象：</strong></p>
<blockquote>
<p>var obj = JSON.parse(str);  // 序列化</p>
</blockquote>
<p><strong>JSON对象转换成JSON字符串：</strong></p>
<blockquote>
<p>var str = JSON.stringify(obj);  // 反序列化</p>
</blockquote>
<hr>
<h2 id="八、this的指向问题"><a href="#八、this的指向问题" class="headerlink" title="八、this的指向问题"></a><div id="title">八、this的指向问题</div></h2><p><strong>javascript中的this有点类似于Python中的self</strong><br><strong>即哪个对象调用当前的方法或属性，那此时this就是哪个对象，但在js中this的指向总共分为三种：</strong></p>
<h3 id="1-this指向window"><a href="#1-this指向window" class="headerlink" title="1.this指向window"></a>1.this指向window</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="keyword">this</span>);</span><br><span class="line"><span class="keyword">var</span> a = <span class="number">10</span>;</span><br><span class="line"><span class="keyword">var</span> b = <span class="number">20</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f1</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">100</span>;</span><br><span class="line">    <span class="keyword">var</span> b = <span class="number">200</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.a);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.b);</span><br><span class="line">&#125;</span><br><span class="line">f1();</span><br></pre></td></tr></table></figure>

<h3 id="2-this指向元素节点对象"><a href="#2-this指向元素节点对象" class="headerlink" title="2.this指向元素节点对象"></a>2.this指向元素节点对象</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> mydiv = <span class="built_in">document</span>.getElementById(<span class="string">'info'</span>);</span><br><span class="line">mydiv.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.innerText);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<div style="display:none;">
### 3.this指向调用该方法的当前对象
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> name = <span class="string">'john'</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">run</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.name + <span class="string">' is running...'</span>);</span><br><span class="line">&#125;</span><br><span class="line">run();</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> jim = &#123;<span class="string">'name'</span>:<span class="string">'jim'</span>, <span class="string">'leg'</span>:<span class="number">4</span>, <span class="string">'age'</span>:<span class="number">28</span>&#125;;</span><br><span class="line">jim.walk = run;</span><br><span class="line">jim.walk();</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="九、词法分析"><a href="#九、词法分析" class="headerlink" title="九、词法分析"></a><div id="title">九、词法分析</div></h2><p><strong>js在调用函数的那一瞬间，会先进行词法分析</strong></p>
<p><strong>词法分析的过程：</strong></p>
<blockquote>
<p>当函数调用的前一瞬间,先形成一个激活对象,叫Avtive Object, AO,并会分析以下3个方面的东西:</p>
<p>1:函数参数，如有，则将此参数付给AO上，并且值为undefined。如没有，则不做任何操作<br>2:函数局部变量，如AO上有，则不做任何操作。如没有，则将此变量赋给AO，并且值为undefined<br>3:函数声明，如AO上有，则会将AO上的对象覆盖。如没有，则不做任何操作</p>
<p><font color="red">函数内部无论是使用参数,还是使用局部变量,都到AO上找.</font></p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">t</span>(<span class="params">age</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(age);</span><br><span class="line">        <span class="keyword">var</span> age = <span class="number">99</span>;</span><br><span class="line">        <span class="built_in">console</span>.log(age);</span><br><span class="line">        <span class="function"><span class="keyword">function</span> <span class="title">age</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">console</span>.log(age);</span><br><span class="line">&#125;</span><br><span class="line">t();</span><br></pre></td></tr></table></figure>

<blockquote>
<p>分析过程：<br>   1、分析参数，有一个参数，形成一个 AO.age=undefine;<br>   2、分析变量声明，有一个 var age, 发现 AO 上面已经有一个 AO.age，因此不做任何处理<br>   3、分析函数声明，有一个 function age(){} 声明， 则把原有的 age 覆盖成 AO.age=function(){};</p>
<p>   最终，AO上的属性只有一个age，并且值为一个函数声明</p>
</blockquote>
<blockquote>
<p>执行过程<br>    注意：执行过程中所有的值都是从AO对象上去寻找</p>
<p>   1、执行第一个 console.log(age) 时，此时的 AO.age 是一个函数，所以第一个输出的一个函数<br>   2、这句 var age=99; 是对 AO.age 的属性赋值， 此时AO.age=99 ，所以在第二个输出的是 99<br>   3、同理第三个输出的是 99, 因为中间没有改变 age 值的语句了</p>
</blockquote>
<p><strong>练习：</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="string">"global"</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span>  <span class="title">t</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(str);</span><br><span class="line">    <span class="keyword">var</span> str = <span class="string">"local"</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(str);</span><br><span class="line">&#125;</span><br><span class="line">t();</span><br></pre></td></tr></table></figure>

</div>

    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、JS如何引入及基本语法规范"><span class="toc-text">一、JS如何引入及基本语法规范</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、变量声明"><span class="toc-text">二、变量声明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、JS变量类型"><span class="toc-text">三、JS变量类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、运算符介绍"><span class="toc-text">四、运算符介绍</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、流程控制"><span class="toc-text">五、流程控制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#六、函数"><span class="toc-text">六、函数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#七、常见的模块和常用方法"><span class="toc-text">七、常见的模块和常用方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-日期类Date"><span class="toc-text">1.日期类Date</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-Math数学对象"><span class="toc-text">2.Math数学对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-常见的其他函数"><span class="toc-text">3.常见的其他函数</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#八、this的指向问题"><span class="toc-text">八、this的指向问题</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-this指向window"><span class="toc-text">1.this指向window</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-this指向元素节点对象"><span class="toc-text">2.this指向元素节点对象</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#九、词法分析"><span class="toc-text">九、词法分析</span></a></li></ol>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2017/05/07/html相关概念/" rel="next" title="第十四章 HTML基础学习目录">
          第十四章 HTML基础学习目录
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2017/05/07/Python编码中出现的问题/" rel="prev" title="python编码">
            python编码
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
